<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small"
          placeholder="输入员工姓名全员搜索" @input="onSearch" />
        <!-- 树形组件 -->

        <el-tree ref="treeRef" highlight-current node-key="id" :data="treeData" :props="{ label: 'name' }"
          default-expand-all :expand-on-click-node="false" @current-change="changeCurrent" />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="isShow = true">excel导入</el-button>

          <el-button size="mini" @click="onExport">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <div v-else class="username">
                {{ row.username.charAt(0) }}
              </div>
            </template>

          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <div>
                {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="160px">
            <template #default="{ row }">
              <el-button v-focus="'show'" size="mini" type="text"
                @click="$router.push('/employee/detail/' + row.id)">查看</el-button>

              <el-button v-focus="'assign'" size="mini" type="text" @click="onSHowRole(row.id)">角色</el-button>
              <el-popconfirm title="确定删除麻" @onConfirm="onDelById(row.id)">
                <template #reference>
                  <el-button v-focus="'del'" size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination layout="total,prev, pager, next" :total="total" :current-page="queryParams.page"
            :page-size="queryParams.pagesize" @current-change="changePage" />
        </el-row>

        <!-- 分页 -->
      </div>
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <!-- 弹层内容 -->
        <!-- checkbox -->
        <el-checkbox-group v-model="roleIds">
          <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>

        </el-checkbox-group>
        <el-row :style="{ padding: '20px' }" type="flex" justify="center">
          <el-button size="mini" type="primary" @click="onAssignRole">分配角色</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>

        </el-row>

      </el-dialog>
    </div>
    <ImportExcel :show-excel-dialog.sync="isShow" />
  </div>
</template>

<script>
import { getDepartmentAPI } from '@/api/department'
import { getEmployeeListAPI, exportAPI, delEmployeeAPI, getEnableRoleListAPI, getEmployeeDetailAPI, assignRoleAPI } from '@/api/employee'
import { arrayToTree } from '@/utils'
import { saveAs } from 'file-saver'
import ImportExcel from './import-excel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      treeData: [],
      depId: null,
      list: [],
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10
      },
      total: 0, // 记录员工的总数
      keyword: '',
      // 3.
      isShow: false,
      // 3.
      showRoleDialog: false,
      roleList: [],
      roleIds: []
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async onAssignRole() {
      await assignRoleAPI({ roleIds: this.roleIds, id: this.userId })
      this.showRoleDialog = false
      this.$message.success('分配角色成功')
    },
    async onSHowRole(id) {
      this.showRoleDialog = true
      // 1. 调用接口, 获取角色列表
      // 2. 显示弹层
      const res = await getEnableRoleListAPI()
      const { roleIds } = await getEmployeeDetailAPI(id)
      this.roleIds = roleIds
      this.roleList = res
      // js弱类型可以任意对象可以分配属性， 只要是对象, 都可以随意分配新属性
      this.userId = id
    },
    async loadData() {
      const res = await getDepartmentAPI()
      const tree = arrayToTree(res)
      this.treeData = tree
      this.depId = tree[0].id

      // 3. 调用查询员工的接口
      this.loadEmployee()
      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(tree[0].id)
      })
    },
    changeCurrent(data) {
      // 5. 保存选中的部门id
      this.depId = data.id
      // 6. 重新 调用查询员工的接口
      this.loadEmployee()
    },
    async loadEmployee() {
      const { rows, total } = await getEmployeeListAPI({ keyword: this.keyword, departmentId: this.depId, page: this.queryParams.page })
      this.list = rows
      // 2. 保存total
      this.total = total
    },
    // 4. 监听页码改边 , 重新请求
    changePage(current) {
      this.queryParams.page = current
      this.loadEmployee()
    },
    onSearch() {
      // 6. 防抖优化
      clearTimeout(this.timerId)
      // JS 弱类型  只要是对象, 都可以随意分配新属性
      this.timerId = setTimeout(() => {
        // 4. 重置为page为1
        this.queryParams.page = 1
        // 5. 重新发请求
        this.loadEmployee()
      }, 500)
    },
    async onExport() {
      // 2. 调用API
      const res = await exportAPI()
      console.log('res  ----->  ', res)
      // 4.
      saveAs(res, '员工信息.xlsx')
    },
    async onDelById(id) {
      await delEmployeeAPI(id)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.loadEmployee()
      this.$message.success('删除成功')
    }
  }
}

</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
